<?php

namespace app\common\service;

use app\common\model\OrderModel;
use think\facade\Cache;
use think\Db;

class ImportOrderService
{
    const CACHE_KEY = 'admin_order_import';

	/**
	 * 接受任务投递
	 * @Author   zhibin3
	 * @DateTime 2022-09-15
	 * @param    [type]     $filePath [description]
	 * @return   [type]               [description]
	 */
	public function import($filePath='')
	{
        ini_set('memory_limit', '1024M');

        if (!empty($filePath)) $data = $this->getData($filePath);
        
        $timestamp = time();
        $OrderModel = new OrderModel();
        Db::startTrans();
        $timestamp = time();
        try {
            foreach ($data as $key => $row) {
                $row['pay_mode'] = OrderModel::get_pay_mode(trim($row['pay_mode']));
                $row['status'] = OrderModel::get_status($row['status']);
                $row['submit_time'] = my_strtotime($row['submit_time']);
                $row['finish_time'] = my_strtotime($row['finish_time']);
                $row['pay_time'] = my_strtotime($row['pay_time']);
                $row['post_time'] = my_strtotime($row['post_time']);

                $order_id = $OrderModel->getValue(['order_sn'=>$row['order_sn']], 'id');
                if (empty($order_id)) {
                    $row['create_time'] = $row['update_time'] = $timestamp;
                    $OrderModel->insert($row);
                } else {
                    unset($row['order_sn']);
                    $OrderModel->where(['id'=>$order_id])->update($row);
                }
            }

            $code = 200;
            $msg = 'Success';
            @unlink($filePath);
            Db::commit();
        } catch (\Exception $e) {
            $code = 500;
            $msg = $e->getMessage();
            @unlink($filePath);
            Db::rollback();
        }
        // $code = 200;$msg = 'Success';

        Cache::rm(self::CACHE_KEY);
        return ['code'=>$code, 'msg'=>$msg];
	}

	/**
	 * 数据插入
	 * @Author   zhibin3
	 * @DateTime 2022-09-15
	 * @param    Object     $currentSheet [description]
	 * @param    [type]     $allRow       [description]
	 * @return   [type]                   [description]
	 */
	public function getData($filePath)
	{
        // $ext = pathinfo($filePath, PATHINFO_EXTENSION);
		$pathinfo = pathinfo($filePath);
        if (!in_array($pathinfo['extension'], ['csv', 'xls', 'xlsx'])) {
            return false;
        }

        $config = [
            'path' => $pathinfo['dirname'], // xlsx文件保存路径
        ];
        $excel  = new \Vtiful\Kernel\Excel($config);

        $data = [];
        // 打开示例文件
        $excel->openFile($pathinfo['basename'])->openSheet('Sheet1')->setSkipRows(1);
        while (($row = $excel->nextRow()) !== NULL) {
            yield 
            $data[] = [
                'order_sn' => (string)$row[0],
                'product_count' => (int)$row[5],
                'product_code' => (string)$row[6],
                'shop_code' => (string)$row[7],
                'price' => (float)$row[8],
                'deal_price' => (float)$row[9],
                'freight' => (float)$row[10],
                'discount_total' => (float)$row[11],
                'discount_platform' => (float)$row[12],
                'discount_business' => (string)$row[13],
                'discount_talent' => (string)$row[15],
                'discount_pay' => (string)$row[16],
                'discount_red' => (string)$row[17],
                'pay_mode' => (string)trim($row[18]),
                'procedures_fee' => (float)$row[19],
                'leave_word' => (string)trim($row[28]),
                'submit_time' => (string)trim($row[29]),
                'remark' => (string)trim($row[31]),
                'finish_time' => (string)trim($row[32]),
                'pay_time' => (string)trim($row[33]),
                'app_from' => (string)$row[34],
                'source_from' => (string)$row[35],
                'status' => (string)$row[36],
                'order_type' => (string)$row[38],
                'talent_code' => (string)$row[40],
                'talent_nickname' => (string)$row[41],
                'ad_channel' => (string)$row[49],
                'post_time' => (string)trim($row[52]),
            ];
        }

        return $data;
	}
}